package com.itheima.controller.request;

import com.itheima.domain.User;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.io.IOException;
import java.util.List;

/**
 * https://docs.spring.io/spring-framework/docs/5.3.19-SNAPSHOT/reference/html/web.html#mvc-ann-arguments
 */
@Controller
public class RequestOtherController {

    /**
     * @TODO 1.需求：页面从请求域中获取值，例如：success.jsp页面中
     * <h1>hello,${name}</h1>
     */
    @RequestMapping(value = "/model")
    public String sayHello() {
        //代表的是逻辑视图
        return "success";
    }

    /**
     * @TODO 2.需求：在springmvc中使用原生态对象request
     */
    @RequestMapping(value = "/servlet")
    public void servlet(HttpServletRequest request, HttpServletResponse response, HttpSession session) throws IOException {
        //1.获取请求uri
        String requestURI = request.getRequestURI();
        System.out.println("requestURI = " + requestURI);
        //2.session会话域中存储用户信息
        session.setAttribute("s1", "s1");
        //3.种cookie并响应给客户端
        Cookie cookie = new Cookie("c1", "java142");
        cookie.setMaxAge(100);
        cookie.setPath("/");
        response.addCookie(cookie);
        //4.直接向客户端响应数据
        response.getWriter().print("servlet response java142 !!");
    }

    /**
     * @TODO 3.需求：用户在页面填写的数据时，除了前端后端也需要校验参数合法性。后端如何完成校验呢？
     * 第1：对哪个对象进行校验 @Valid User
     * 第2：校验的规则是怎么样 @Min @Max @NotBlank  @NotNull 放在需要校验的属性上即可
     * 第3：校验结果BindingResult 封装了校验结果（哪个属性违反规则）
     */
    @RequestMapping("/valid")
    public String valid(@Valid User user, BindingResult result) {
        //FieldError=哪个属性出错（age）+出错提示信息是什么(年龄最小是18岁)
        List<FieldError> fieldErrors = result.getFieldErrors();
        fieldErrors.forEach(fe -> {
            String field = fe.getField();
            String message = fe.getDefaultMessage();
            System.out.println("field===>" + field + ",message====>" + message);
        });
        return "success";
    }

}
